/*
 * Copyright (c) 2015 Uwantsoft Ltd.
 * www.uwantsoft.com
 * All rights reserved.
 * This software is the confidential and proprietary information of
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with Uwantsoft.
 */

package com.uwantsoft.business.infrastructure.repository.querier;

import com.uwantsoft.business.facade.dto.parking.CityOverviewQueryCondition;
import com.uwantsoft.business.service.domain.city.City;
import com.uwantsoft.util.paging.AbstractQuerier;
import com.uwantsoft.util.paging.Filter;
import com.uwantsoft.util.paging.ParameterFilter;
import org.hibernate.Query;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.util.StringUtils;

/**
 * @author Leipeichen.
 */
public class CityOverviewQuerier extends AbstractQuerier<City>{

    private CityOverviewQueryCondition cityOverviewQueryCondition;

    public CityOverviewQuerier(HibernateTemplate hibernateTemplate, CityOverviewQueryCondition condition) {
        super(hibernateTemplate);
        this.cityOverviewQueryCondition = condition;
        addCodeFilter();
    }

    private void addCodeFilter() {
        final String code = cityOverviewQueryCondition.getCode();
        if(StringUtils.hasText(code)){
            addFilter(new ParameterFilter() {
                @Override
                public void setParameter(Query query) {
                    query.setParameter("code","%"+code+"%");
                }
                @Override
                public String getSubHql() {
                    return "and c.code like :code";
                }
            });
        }
    }


    @Override
    public int getStartPosition() {
        return cityOverviewQueryCondition.getStartIndex();
    }

    @Override
    public int getItemsAmountPerPage() {
        return cityOverviewQueryCondition.getObjectsPerPage();
    }


    @Override
    public String getResultHql() {
        return "from City c where 1=1 " + getSubHql();
    }

    @Override
    public String getAmountHql() {
        return "select count(*) from City c where 1=1 " + getSubHql();
    }
}
